<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\User;
use App\Model\Work;

use App\Model\WorkPush;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;
use Hyperf\DbConnection\Db;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class WorkController extends AppBaseController
{
    /**
     * 后台--党务公开列表
     * @return object
     */
    #[RequestMapping(path:'workList',methods: 'get')]
    public function workList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            $list = Work::with(['party'=>function($query){
                    $query->selectRaw('id,name')->get();
                }])->where($where)
                ->selectRaw('id,party_id,title,status,pass_status,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Work::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--党务公开详情
     * @param int $work_id
     * @return object
     */
    #[RequestMapping(path:'workInfo/{work_id}',methods: 'get')]
    public function workInfo(int $work_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = Work::where('id',$work_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--党务公开发布|编辑
     * @param int|null $work_id
     * @return object
     */
    #[RequestMapping(path: 'workEdit[/{work_id}]',methods: 'post,get')]
    public function workEdit(int|null $work_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){

//                $data['push_type'] = 0;
//                $data['push_time'] = '2024-10-01 12:12:12';

//                $data['title'] = '或那个风格二个人哥哥';
//                $data['photo'] = 'fqxinyi23/test/xyWords/xyWords1691110928830.jpg';
//                $data['content'] = '学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习学习';
//                $data['media_list'] = [
//                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                ];
//                $data['file_list'] = [
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com'],
//                    ['name'=>'ceshi1','url'=>'https://www.baidu.com']
//                ];
//                $data['status'] = 1;
//            }
            //虚拟数据

            //push_type 0：全部 1：党员 2：支部委员
//            if(!isset($data['push_type']) || !in_array($data['push_type'],[0,1,2])) return $this->reMsg->re(10007,'推送对象有误');

            if(empty($data['title'])
            ){
                return $this->reMsg->re(10007);
            }


            if(empty($data['photo'])) $data['photo'] = null;
            if(empty($data['content'])) $data['content'] = null;
            if(empty($data['media_list']) || !is_array($data['media_list'])) $data['media_list'] = [];
            if(empty($data['file_list']) || !is_array($data['file_list'])) $data['file_list'] = [];

            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //指定支部
            //指定支部
            if($_admin->level==1){
                if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
                $party_id = $data['party_id'];
            }else{
                $party_id = $_admin->party_id;
            }

            Db::beginTransaction();

            if($work_id){
                //编辑
                $info = Work::where('id',$work_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //判断是否有权操作
                if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);

                $info->title = $data['title'];
                $info->photo = $data['photo'];
                $info->content = $data['content'];
                $info->media_list = $data['media_list'];
                $info->file_list = $data['file_list'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                Db::commit();
                return $this->reMsg->re(1);
            }else{
//                $nowDate = date('Y-m-d H:i:s',time());
//                if($data['push_time']<$nowDate){
//                    return $this->reMsg->re(10007,'推送时间应大于当前时间');
//                }

                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                Work::create($data);
                Db::commit();
                return $this->reMsg->re(1);


//                $insertRet = Work::create($data);
//                if($insertRet){
//                    $push_uid_arr = [];
//                    //创建成功进行推送，根据push_type获取推送对象
//                    $userTypeIn = [8,9];
//                    if($data['push_type']==0){
//                        $userTypeIn = [1,2,8,9];
//                    }
//                    if($data['push_type']==1){
//                        $userTypeIn = [2,8,9];
//                    }
//                    if($data['push_type']==2){
//                        $userTypeIn = [8,9];
//                    }
//
//                    //获取对应用户id
//                    $uidIds = User::whereNotNull('auth_time')->whereIn('user_type',$userTypeIn)->pluck('id')->toArray();
//                    $push_uid_arr = array_merge($push_uid_arr,$uidIds);
//                    if($push_uid_arr){
//                        $pushData = [];
//                        $i=0;
//                        foreach ($push_uid_arr as $uKey=>$uVal){
//                            $pushData[$i]['party_id'] = $party_id;
//                            $pushData[$i]['work_id'] = $insertRet->id;
//                            $pushData[$i]['uid'] = $uVal;
//                            $pushData[$i]['push_time'] = $nowDate;
//                            $pushData[$i++]['created_at'] = $nowDate;
//                        }
//                        Db::table('work_push')->insert($pushData);
//                    }
//                    Db::commit();
//                    return $this->reMsg->re(1);
//                }else{
//                    Db::rollBack();
//                    return $this->reMsg->re(0);
//                }
            }
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     *  后台--党务公开|审核通过
     * @param int $work_id
     * @return object
     */
    #[RequestMapping(path:'workPass/{work_id}',methods: 'get')]
    public function workPass(int $work_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Work::where('id',$work_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);
            $info->pass_status = 1;
            $info->save();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }

    /**
     * 后台--党务公开|删除
     * @param int $work_id
     * @return object
     */
    #[RequestMapping(path:'workDelete/{work_id}',methods: 'get')]
    public function workDelete(int $work_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Work::where('id',$work_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限
            if($_admin->level!=1 && $_admin->party_id!=$info->party_id) return $this->reMsg->re(10009);

            Db::beginTransaction();
            //删除用户推送的work
            $pushWhere['work_id'] = $info->id;
            WorkPush::where($pushWhere)->delete();

            $info->delete();

            Db::commit();
            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            Db::rollBack();
            return $this->diyError->errorJson($exception);
        }
    }





}